import { useSearchParams } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '../../../hooks/store'
import { useEffect, useState } from 'react'
import { FileImageOutlined, MoreOutlined, PlusCircleOutlined } from '@ant-design/icons'
import UserMenuItem, { AppMenuItemAction } from './UserMenuItem'
import { CreateFavoriteRequest, UpdateFavoriteRequest } from '../../../api/favorite'
import { createFavorite, deleteFavorite, favoriteIdChange, fetchFavorites, updateFavorite } from '../../../store/slice/favorite'
import { detailReset } from '../../../store/slice/picture'
import UserMenu from './UserMenu'
import { Modal } from 'antd'
import FavoriteFormModal from './FavoriteFormModal'

const UserFavoriteMenu:React.FC = () => {
    const [searchParams, setSearchParams] = useSearchParams()
    const dispatch = useAppDispatch()
    const favoriteState = useAppSelector((state) => state.favorite)
    const [createFormOpen, setCreateFormOpen] = useState<boolean>(false)
    const [updateFormOpen, setUpdateFormOpen] = useState<boolean>(false)
    const [deleteFormOpen, setDeleteFormOpen] = useState<boolean>(false)
    const [initialValues, setinitialValues] = useState<Partial<UpdateFavoriteRequest>>()
    const items = favoriteState.list.map((c) => ({
        key: c.id.toString(),
        icon: <FileImageOutlined />,
        label: c.name,
    }))
    const actions: AppMenuItemAction[] = [
        { label: '编辑', onClick: () => { setUpdateFormOpen(true) } },
        { label: '删除', onClick: () => { setDeleteFormOpen(true) }, danger: true }
    ]
    const onCreate = (values: CreateFavoriteRequest) => {
        dispatch(createFavorite(values))
        setCreateFormOpen(false)
    }
    const onUpdate = (values: UpdateFavoriteRequest) => {
        values.id = Number(favoriteState.current)
        dispatch(updateFavorite(values))
        setUpdateFormOpen(false)
    }
    const onDelete = () => {
        dispatch(deleteFavorite({ id: Number(favoriteState.current) }))
        setDeleteFormOpen(false)
    }
    useEffect(() => {
        if (favoriteState.status === 'idle') {
            dispatch(fetchFavorites())
        } else if (favoriteState.status === 'succeeded') {
            const selectedFavorite = favoriteState.list.find((c) => c.id === favoriteState.current)
            if (selectedFavorite) {
                setinitialValues({
                    id: selectedFavorite.id,
                    name: selectedFavorite.name,
                    desc: selectedFavorite.desc,
                })
            }
        }
    }, [favoriteState, dispatch])
    useEffect(() => {
        const favoriteId = searchParams.get('favorite_id')
        dispatch(favoriteIdChange(Number(favoriteId) || 0))

        if (Number(favoriteId) !== favoriteState.current) {
            dispatch(detailReset())
        }
    }, [favoriteState, dispatch, searchParams])
    return (
        <>
            <Modal open={deleteFormOpen} onOk={onDelete} title='删除文件夹' children='确认删除此图片文件夹？' cancelText='取消' onCancel={() => setDeleteFormOpen(false)} />
            <FavoriteFormModal name='create' open={createFormOpen} onOK={onCreate} onCancel={() => setCreateFormOpen(false)} title='创建文件夹' />
            {updateFormOpen && <FavoriteFormModal name='update' open={updateFormOpen} onOK={onUpdate} onCancel={() => setUpdateFormOpen(false)} title='编辑文件夹' initialValues={initialValues} />}
            <UserMenuItem
                icon={<PlusCircleOutlined />}
                onClick={() => setCreateFormOpen(true)}
            >
                新建收藏夹
            </UserMenuItem>
            <UserMenu
                actions={actions}
                actionIcon={<MoreOutlined />}
                defaultSelectedKey={searchParams.get('favorite_id') || '0'}
                selectedKey={favoriteState.current?.toString()}
                style={{ height: '100%' }}
                items={items}
                onClick={(e) => {
                    setSearchParams({
                        favorite_id: e.key
                    })
                }}
            />
        </>
    )
}

export default UserFavoriteMenu